﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Criterion;
using Dukous.Search;
using Dukous.Dao.NHibernate;
using Dukous.Security.Domain;

namespace Dukous.Security.Dao.NHibernate
{
    public class GroupDao : EntityDao<Group, long>, IGroupDao, ISearchSupport<Group>
    {
        #region ISearchSupport<Group> 成员

        public IList<Group> SelectBySearch(ISearchContext context, out int totalCount)
        {
            int count = 0;
            IList<Group> groups = this.HibernateTemplate.ExecuteFind<Group>(delegate(ISession session)
            {

                ICriteria criteria = session.CreateCriteria(typeof(Group), "g");

                count = criteria.SetProjection(Projections.Count("Id").SetDistinct()).UniqueResult<int>();
                if (count == 0)
                {
                    return new List<Group>();
                }

                criteria.SetProjection(new IProjection[] { null });
                criteria.SetResultTransformer(CriteriaSpecification.DistinctRootEntity);

                return criteria.SetFirstResult(context.PageSize * (context.PageIndex - 1))
                        .SetMaxResults(context.PageSize)
                        .AddOrder(new global::NHibernate.Criterion.Order("Id", false))
                        .List<Group>();
            });

            totalCount = count;

            return groups;
        }

        #endregion

        public Group FindByName(string name)
        {
            return this.HibernateTemplate.Find<Group>("from Group g where g.GroupName = ?", name).FirstOrDefault();
        }
    }
}
